<?php

include_once('class.mysql.php');

class Login
{
    private $_id;
    private $_username;
    private $_password;
    private $_passmd5;

    private $_errors;
    private $_access;
    private $_login;
    private $_token;

    public function __construct()
    {
        $this->_errors  = array();
        $this->_login   = isset($_POST['login'])? 1 : 0;
        $this->_access  = 0;
        $this->_token   = $_POST['token'];
        $this->_id      = 0;

        $this->_username = ($this->_login)? $this->filter($_POST['username']) : $_SESSION['username'];
        $this->_password = ($this->_login)? $this->filter($_POST['password']) : '';
        $this->_passmd5  = ($this->_login)? md5($this->_password) : $_SESSION['password'];

    }

    public function isLoggedIn()
    {
        ($this->_login)? $this->verifyPost() : $this->verifySession();

        return $this->_access;
    }

    public function filter($var)
    {
        return preg_replace('/[^a-zA-Z0-9@.]/','',$var);
    }

    public function verifyPost()
    {
        try
        {
            if(!$this->isTokenValid())
                throw new Exception('Formulario inv&aacute;lido');

            if(!$this->isDataValid())
                throw new Exception('Datos inv&aacute;lidos');

            if(!$this->verifyDatabase())
                throw new Exception('Nombre de usuario y contrase&ntilde;a inv&aacute;lidos');

            $this->_access = 1;
            $this->registerSession();
        }
        catch (Exception $e)
        {
            $this->_errors[] = $e->getMessage();
        }
    }

    public function verifySession()
    {
        if($this->sessionExist() && $this->verifyDatabase())
            $this->_access = 1;
    }

    public function verifyDatabase()
    {
        $mysql = new MySQL();

        $data = $mysql->query("SELECT id_usuario FROM usuarios WHERE correo = '{$this->_username}' AND contrasena = '{$this->_passmd5}'");

        if ($mysql->num_rows($data))
        {
            list($this->_id) = @array_values($mysql->fetch_assoc($data));
            return true;
        }
        else
            { return false; }
    }

    public function isDataValid()
    {
        return (preg_match('/^[a-zA-Z0-9@.]/',$this->_username) && preg_match('/^[a-zA-Z0-9@.]/',$this->_password))? 1 : 0;
    }

    public function isTokenValid()
    {
        return (!isset($_SESSION['token']) || $this->_token != $_SESSION['token'])? 0 : 1;
    }

    public function registerSession()
    {
    
        if (isset($_POST['remember_me']))
        {
            setcookie("session_id",$this->_id,time()+60*60*24*30,"/");
        }
        else
        {
            $_SESSION['cid'] = $this->_id;
        }
    }

    public function isCookieSet()
    {
        return (isset($_COOKIE['session_id']) && $_COOKIE['session_id'] != "")? 1 : 0;
    }

    public function sessionExist()
    {
        return (isset($_SESSION['cid']))? 1 : 0;
        /*return (isset($_SESSION['cid']) || isset($_COOKIE['session_id']))? 1 : 0;*/
    }

    public function showErrors()
    {
        echo "<h3>Errores</h3>";
        foreach($this->_errors as $key=>$value)
            echo $value."<br>";
    }

    public function giveId()
    {
        if (isset($_SESSION['cid']))
            return $_SESSION['cid'];

        if (isset($_COOKIE['session_id']))
            return $_COOKIE['session_id'];

        return $this->_id;
    }
}

?>
